<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Model;

/**
 * App\Models\UserAddress
 *
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress query()
 * @mixin \Eloquent
 * @property int $id
 * @property int $user_id 用户ID
 * @property string $name 收货人姓名
 * @property string $phone 电话
 * @property string $area 所在地区
 * @property string|null $address 收货地址
 * @property int $is_default 是否默认:0=否,1=是
 * @property \Illuminate\Support\Carbon|null $created_at
 * @property \Illuminate\Support\Carbon|null $updated_at
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereAddress($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereArea($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereCreatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereId($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereIsDefault($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereName($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress wherePhone($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereUpdatedAt($value)
 * @method static \Illuminate\Database\Eloquent\Builder|UserAddress whereUserId($value)
 * @property-read \App\Models\User|null $user
 */
class UserAddress extends Model
{
	use HasDateTimeFormatter;
    protected $table = 'user_address';

    protected static function booted()
    {
        self::creating(function (UserAddress $car){
            $exists = self::query()->where("user_id", $car->user_id)->exists();
            if (!$exists){
                $car->is_default = 1;
            }
        });
        self::saved(function(UserAddress $row){
            if ($row->is_default){
                self::query()
                    ->where("id","<>",$row->id)
                    ->where("user_id",$row->user_id)
                    ->update(['is_default'=>0]);
            }
        });
        self::deleted(function (UserAddress $row){
            if ($row->is_default){
                self::query()
                    ->where("user_id",$row->user_id)
                    ->orderByDesc("id")
                    ->limit(1)
                    ->update(['is_default'=>1]);
            }
        });
    }

    public function user(){
        return $this->hasOne(User::class,"id","user_id");
    }

}
